import { _decorator, Component, Sprite, SpriteFrame, log, Input, EventTouch, UITransform, Vec3, Node, tween, find } from 'cc';
import { TableauPile } from './TableauPile';
const { ccclass, property } = _decorator;

@ccclass('Card')
export class Card extends Component {
    @property(Sprite)
    sprite: Sprite = null;

    public suit: string = '';       // 花色'hearts', 'spades', 'diamonds', 'clubs'
    public rank: number = 0;        // 数字 1-13

    @property(Card)
    public preCard: Card = null;
    @property(Card)
    public nextCard: Card = null;

    private _originalPos: Vec3 = new Vec3();

    @property([SpriteFrame])
    cardFaces: SpriteFrame[] = [];
    @property(SpriteFrame)
    cardBack: SpriteFrame = null;

    isFaceUp: boolean = false;

    @property(TableauPile)
    public tableauPile: TableauPile = null;
    protected onLoad(): void {

    }
    start() {
        this.sprite.spriteFrame = this.cardBack;
    }


    private getFaceSpriteFrame(): SpriteFrame | null {
        const suitOrder = ['hearts', 'spades', 'diamonds', 'clubs'];
        let suitIndex = suitOrder.indexOf(this.suit);
        if (suitIndex === -1) {
            log('未知的花色: ' + this.suit);
            return null;
        }

        const index = suitIndex * 13 + (this.rank - 1);
        return this.cardFaces[index] || null;
    }

    public returnOriginalPos() {
        this.node.setPosition(this._originalPos);
    }



    public flip() {
        this.isFaceUp = !this.isFaceUp;
        if (this.isFaceUp) {
            let face = this.getFaceSpriteFrame();
            if (face) {
                this.sprite.spriteFrame = face;
            } else {
                log('未找到对应正面图片');
            }
        } else {
            this.sprite.spriteFrame = this.cardBack;
        }
    }

    public moveTo(position: Vec3, duration: number = 0.2, callback?: Function) {
        tween(this.node)
            .to(duration,
                { position: position },
                { easing: 'sineOut' }
            )
            .call(() => callback && callback())
            .start();
    }

    public setPreCard(card: Card) {
        this.preCard = card;
    }

    public setNextCard(card: Card) {
        this.nextCard = card;
    }
}
